home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1410 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: getchar() problems!
  5. Date: 13 Jan 1996 17:30:45 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4d8q85$mqc@news.iag.net>
  8. References: <DL2wFD.8BK@cdf.toronto.edu>
  9. NNTP-Posting-Host: pm2-orl20.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <DL2wFD.8BK@cdf.toronto.edu>, a228lave@cdf.toronto.edu says...
  13.  
  14. <Sorry to have snipped meaningful code, but IAG has decided to enforce that
  15. blasted quoted to new lines ration.  I'll have to find a new ISP.>
  16.  
  17. >   printf("Please enter a series of chars.  Type '#' to quit.\n");
  18. >   while ((ch=getchar()) != '#')
  19. >      {
  20. >         switch (ch)
  21. >            {
  22. >               case SPACE: sp_c++; break;
  23. >               case NL   : nl_c++; break;
  24. >               default   : ot_c++;
  25. >            }
  26. >      }
  27. >   printf("There were %d spaces, %d newlines, and %d other                      
  28. >chars!",sp_c,nl_c,ot_c);
  29. >   ch=getchar();
  30. >}
  31. >
  32. >}
  33. >
  34. >What _actually_ happens is the code takes characters until you hit the #, and 
  35. >then continues until you press return.  Also, the final ch=getchar(); line
  36. >appears to be ignored... it's intended as a pause.  I'm somewhat of a 
  37. beginner
  38. >to the language, so any help will be greatly appreciated!
  39.  
  40. Your problems are arising from the fact that keyboard input is line bufferred.
  41. No input is fed to your code until the user pressed return. Then the entire
  42. line is made available.  In your code, getchar() reads one char at a time 
  43. from the buffer, until it reads a '#'.  At that point it exits the loop and
  44. prints the stats.  When you call the last getchar() (for your pause), it 
  45. simply reads the next char in the same buffer (you know that there is at
  46. least a '\n' left in it).  So, you don't see a pause.
  47.  
  48. The c.l.c faq (Frequently Asked Question) list has a very good explanation
  49. of this and several possible solutions (all are system specific. There is 
  50. no ansi solution, if you want unbufferred input) in Q19.1.  It is available 
  51. for anonymous ftp from rtfm.mit.edu /pub/usenet/comp.lang.c.
  52.  
  53. -- 
  54. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  55. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  56.  
  57.